import logging

import schedule
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt

from Browser.views import *
from FS_RPA import settings
from feishu.feishu_bitable import FeishuBiTable
from .until import update_feishu_tables

logger = logging.getLogger(__name__)


# 表1->表2的筛选素人接口
@csrf_exempt
def feishu_bitable_start(request):
    if request.method != 'POST':
        return JsonResponse({
            "code": 405,
            "message": "仅支持POST方法"
        })

    try:
        data = json.loads(request.body)
        table_id1 = data.get('table_id1')
        table_id2 = data.get('table_id2')
        field_name = data.get('field_name')
        field_value = data.get('field_value')
        app_token = data.get('app_token')
        if table_id1 is None and table_id2 is None:
            return JsonResponse({
                "code": 400,
                "message": "缺少table_id参数"
            })

        # 初始化飞书表格操作类
        feishu_bitable = FeishuBiTable(
            app_config=settings.FEISHU_APP_CONFIGS,
            app_token=settings.APP_TOKEN
        )

        # 获取表格记录
        result1 = feishu_bitable.get_single_record_by_unique_field(table_id=table_id1,
                                                                   field_name=field_name, field_value=field_value)
        records1 = result1.get('fields', {})
        record_id = result1.get('record_id', '')

        if not records1:
            return JsonResponse({
                "code": 200,
                "message": "没有找到记录",
                "data": []
            })

        extracted = {
            '小红书昵称': records1.get('小红书昵称', [{}])[0].get('text', ''),
            'ID号': records1.get('ID号', [{}])[0].get('text', ''),
            '团队账号': records1.get('团队账号', [{}])[0].get('text', ''),
            '顺序': records1.get('顺序', 0),
            '粉丝量': records1.get('粉丝量', 0),
            '赞藏量': records1.get('赞藏量', 0),
            '小红书主页链接': records1.get('小红书主页链接', {}).get('link', ''),
            'record_id': record_id
        }

        extracted['小红书主页链接'] = {
            'link': extracted['小红书主页链接'],
            'text': ''
        }

        fields = [{
            '小红书昵称': extracted['小红书昵称'],
            '顺序': extracted['顺序'],
            'ID号': extracted['ID号'],
            '粉丝量': extracted['粉丝量'],
            '赞藏量': extracted['赞藏量'],
            '团队账号': extracted['团队账号'],
            '小红书主页链接': extracted['小红书主页链接'],
        }]

        result2 = feishu_bitable.add_batch_record(
            table_id=table_id2,
            fields=fields,
            # image_field_name="发布截图",
            # image_path=screenshot_path
        )

        return JsonResponse({
            'code': 200,
            'message': '记录添加成功',
        })

    except Exception as e:
        logger.error(f"处理失败：{str(e)}", exc_info=True)
    return JsonResponse({
        "code": 500,
        "message": "处理失败"
    })


# 表2->表3 and 表4 任务开始的接口
@csrf_exempt
def feishu_bitable_insert(request):
    if request.method != 'POST':
        return JsonResponse({
            "code": 405,
            "message": "仅支持POST方法"
        })

    try:
        data = json.loads(request.body)
        table_id2 = data.get('table_id2')
        table_id3 = data.get('table_id3')
        table_id4 = data.get('table_id4')
        # table_id2 = TABLE_ID2
        # table_id3 = TABLE_ID3
        # table_id4 = TABLE_ID4

        if not table_id3 and table_id2 and table_id4:
            return JsonResponse({
                "code": 400,
                "message": "缺少table_id参数"
            })

        # 初始化飞书表格操作类
        feishu_bitable = FeishuBiTable(
            app_config=settings.FEISHU_APP_CONFIGS,
            app_token=settings.APP_TOKEN
        )

        # 获取表格记录
        result2 = feishu_bitable.get_batch_records(table_id=table_id2)
        records2 = result2.get('data', {}).get('items', [])

        if not records2:
            return JsonResponse({
                "code": 200,
                "message": "没有找到记录",
                "data": []
            })
        updated_records2 = []
        for record in records2:
            fields = record.get('fields', {})
            record_id = record.get('record_id')

            # 提取字段
            extracted = {
                '小红书昵称': fields.get('小红书昵称', [{}])[0].get('text', ''),
                '顺序': fields.get('顺序'),
                'ID号': fields.get('ID号', [{}])[0].get('text', ''),
                '粉丝量': fields.get('粉丝量', 0),
                '赞藏量': fields.get('赞藏量', 0),
                '团队账号': fields.get('团队账号', [{}])[0].get('text', ''),
                '发布链接': fields.get('发布链接', {}).get('link', ''),
                '小红书主页链接': fields.get('小红书主页链接', {}).get('link', ''),
                '发布截图': fields.get('发布截图', {}).get('link', ''),
                '收藏量': fields.get('收藏量', {}).get('text', ''),
                '分享': fields.get('分享', {}).get('text', ''),
                '点赞量': fields.get('点赞量', {}).get('text', ''),
                '评论量': fields.get('评论量', {}).get('text', ''),
                'record_id': record_id
            }

            if extracted['发布链接']:
                insert_stats = browser_process(
                    table_id2=table_id2,
                    table_id3=table_id3,
                    table_id4=table_id4,
                    url=extracted['发布链接'],
                    need_fields=['发布截图', '收藏量', '点赞量', '评论量', '分享']
                )

                # 更新数据
                if insert_stats and isinstance(insert_stats, dict):
                    extracted['发布链接'] = {
                        'link': extracted['发布链接'],
                        'text': ''
                    }
                    extracted['小红书主页链接'] = {
                        'link': extracted['小红书主页链接'],
                        'text': ''
                    }

                    extracted['发布截图'] = insert_stats.get('发布截图')
                    extracted['点赞量'] = insert_stats.get('点赞量', extracted['点赞量'])
                    extracted['收藏量'] = insert_stats.get('收藏量', extracted['收藏量'])
                    extracted['评论量'] = insert_stats.get('评论量', extracted['评论量'])
                    extracted['分享'] = insert_stats.get('分享', extracted['分享'])

                    fields = [{

                        '小红书昵称': extracted['小红书昵称'],
                        '顺序': extracted['顺序'],
                        'ID号': extracted['ID号'],
                        '粉丝量': extracted['粉丝量'],
                        '赞藏量': extracted['赞藏量'],
                        '团队账号': extracted['团队账号'],
                        '发布链接': extracted['发布链接'],
                        '小红书主页链接': extracted['小红书主页链接'],
                        '发布截图': extracted['发布截图'],
                        '收藏量': extracted['收藏量'],
                        '点赞量': extracted['点赞量'],
                        '评论量': extracted['评论量'],
                        '分享': extracted['分享']
                    }]

                    result3 = feishu_bitable.add_batch_record(
                        table_id=table_id3,
                        fields=fields,
                        # image_field_name="发布截图",
                        # image_path=screenshot_path
                    )
                    result4 = feishu_bitable.add_batch_record(
                        table_id=table_id4,
                        fields=fields,
                        # image_field_name="发布截图",
                        # image_path=screenshot_path
                    )

        return JsonResponse({
            'code': 200,
            'message': '记录添加成功',
        })

    except Exception as e:
        logger.error(f"处理失败：{str(e)}", exc_info=True)
        return JsonResponse({
            "code": 500,
            "message": f"处理失败：{str(e)}"
        })


# 表3 and 表4 定时任务的接口
def feishu_bitable_update_from_insert(request):
    """
    接口：手动触发飞书表格更新
    同时兼容定时任务调用
    """
    if request.method != 'POST':
        return JsonResponse({
            "code": 405,
            "message": "仅支持POST方法"
        })
    # data = json.loads(request.body)
    # table_id3 = data.get('table_id3')
    # table_id4 = data.get('table_id4')

    try:
        result = update_feishu_tables()

        if result["success"]:
            return JsonResponse({
                "code": 200,
                "message": "处理成功",
                "data": result["data"]
            })
        else:
            return JsonResponse({
                "code": 500,
                "message": f"处理失败：{result['error']}"
            })

    except Exception as e:
        logger.error(f"接口调用失败：{str(e)}")
        return JsonResponse({
            "code": 500,
            "message": f"接口异常：{str(e)}"
        })
